package spring.cloud.tasks.executor.listener.election;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.listener.ListenerHolder;
import spring.cloud.tasks.executor.node.TaskNodePaths;
import spring.cloud.tasks.executor.task.TaskExecutor;

/**
 * 主节点选举监听管理器.
 */
@Slf4j
@Setter
@Getter
public class ElectionListenerHolder extends ListenerHolder {
    public final LeaderElectionService leaderElectionService;

    public boolean isShutdown;

    public ElectionListenerHolder(final TaskExecutor taskExecutor) {
        super(taskExecutor);
        leaderElectionService = new LeaderElectionService(taskExecutor);
    }

    @Override
    public void start() {
        nodeCacheOrTreeCacheManager.addNodeCacheListener(TaskNodePaths.getTaskNodePath(taskId, ElectionNode.LEADER_HOST), new LeaderElectionTaskListener(this));
    }

    @Override
    public void stop() {
        isShutdown = true;
        leaderElectionService.stop();
        nodeCacheOrTreeCacheManager.closeNodeCache(TaskNodePaths.getTaskNodePath(taskId, ElectionNode.LEADER_HOST));
    }

}
